package cn.tedu.order.tx;

import cn.tedu.order.entity.Order;
import cn.tedu.order.mapper.TxMapper;
import cn.tedu.order.util.JsonUtil;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

@Component
@RocketMQTransactionListener
public class TxListener implements RocketMQLocalTransactionListener {
    @Autowired
    private TxOrderService txOrderService;
    @Autowired
    private TxMapper txMapper;

    //执行本地事务
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        //两个参数：1.发送的事务消息  2.业务数据

        RocketMQLocalTransactionState state;
        int status;

        try {
            Order order = (Order) o;
            txOrderService.doCreate(order);
            state=RocketMQLocalTransactionState.COMMIT;
            status=0;
        }catch (Exception e){
            state=RocketMQLocalTransactionState.ROLLBACK;
            status=1;
        }

        String json = new String((byte[])message.getPayload());
        String xid = JsonUtil.getString(json, "xid");

        TxInfo txInfo = new TxInfo(xid,status,System.currentTimeMillis());

        txMapper.insert(txInfo);
        return state;
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        String json = new String((byte[])message.getPayload());
        String xid = JsonUtil.getString(json, "xid");

        if(!txMapper.exists(xid)){
            return RocketMQLocalTransactionState.UNKNOWN;
        }

        TxInfo txInfo = txMapper.selectById(xid);
        //0-commit   1-rollback  2-unknown
        switch (txInfo.getStatus()){
            case 0:return RocketMQLocalTransactionState.COMMIT;
            case 1:return RocketMQLocalTransactionState.ROLLBACK;
            default:return RocketMQLocalTransactionState.UNKNOWN;
        }
    }
}
